#!/usr/bin/python
# -*- encoding: utf8 -*-

import sys
import os
from optparse import OptionParser

import post


def main(in_filename, out_filename, options):
    """\
    %prog [options] INPUT_FILE [OUTPUT_FILE]

    INPUT_FILE : the file contains wiki codes.
    OUTPUT_FILE: write the translated results to it. Default is stdout.


    The wiki formatting is almost compatible to Trac's wiki formatting.
    For more information, please refer to http://trac.edgewall.org/wiki/WikiFormatting .
    """

    try:
        text = unicode(open(in_filename).read(), 'utf8')
    except IOError, e:
        print >>sys.stderr, "ERROR: cannot open %s. %s" % (in_filename, e.strerror)
        return 2

    if options.bracket:
        post.flags['use_chinese_bracket'] = True

    if options.ignore_missing_link:
        post.flags['ignore_missing_link'] = True

    result = post.parse(text)

    if options.more:
        lines = result.split('\n')
        result = "\n".join(lines[0:1] + ['\n<!--more-->\n'] + lines[1:])
    if options.quine:
        result = result.replace("_QUINE_", text)

    fw = sys.stdout
    if out_filename:
        fw = open(out_filename, 'w')
    fw.write((result + "\n").encode('utf8'))
    fw.close()

    return 0

if __name__ == '__main__':
    parser = OptionParser(usage=main.__doc__)
    parser.add_option("-q", "--quine",
                      action="store_true", dest="quine",
                      help="Replace the string _QUINE_ in INPUT_FILE by the whole content of INPUT_FILE.")
    parser.add_option("-m", "--more",
                      action="store_true", dest="more",
                      help="Add <!--more--> after the first line (paragraph).")
    parser.add_option("-b", "--bracket",
                      action="store_true", dest="bracket",
                      help="Allow to use Chinese brackets for hyper links.")
    parser.add_option("-i", "--ignore-missing-link",
                      action="store_true", dest="ignore_missing_link",
                      help=("Don't exit the program when there is any missing link in [...]."
                            " This is useful when you want to use [...], but actually it's not a link."))
    (options, args) = parser.parse_args()

    if len(args) < 1 or len(args) > 2:
        parser.print_help()
        sys.exit(1)

    if len(args) == 1:
        args.append(None)

    args.append(options)

    try:
        sys.exit(main(*args))
    except SyntaxError, e:
        print >>sys.stderr, ">>> Failed to translate the input.\n"
        print >>sys.stderr, e.message.encode('utf8')
        print >>sys.stderr, ""
        sys.exit(3)
